package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDto;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;
    @GetMapping("hi")
    public String hi() {
        return "hi";
    }
    //请求参数 page size
    @GetMapping("/list")
    public PageDTO<Item> queryItemByPage (@RequestParam("page") Integer page,
                                          @RequestParam("size") Integer size){
        //调用Service进行分页查询
        Page<Item> page1 = itemService.page(new Page<>(page, size));
        //封装返回结果
        return new PageDTO<>(page1.getTotal(), page1.getRecords());
    }
    //根据id查询 @PathVariable("id")绑定路径
    @GetMapping("{id}")
    public Item queryItemById(@PathVariable("id") Long id){
        return itemService.getById(id);
    }
    //根据价格范围查找
    @GetMapping("/query")
    public List<Item> queryItemById(@RequestParam("minPrice") Integer minPrice,
                                    @RequestParam("maxPrice") Integer maxPrice,
                                    @RequestParam("category") String category){
        return itemService.query()
                .eq("category",category)
                .ge("minPrice",minPrice)
                .le("maxPrice",maxPrice).list();
    }
    //新增商品
    @PostMapping
    public void saveItem(@RequestBody Item item){
        //商品创建时间
        item.setCreateTime(new Date());
        //商品更新时间
        item.setUpdateTime(new Date());
        //将商品状态更改为2 上架
        item.setStatus(2);
        itemService.save(item);
    }
    //修改商品状态 上下架商品
    @PutMapping("/status/{id}/{status}")
    public void updateItemStatus(@PathVariable("id") Long id,@PathVariable("status") Integer status){
        itemService.updateItemStatus(id,status);
    }
    //修改商品
    @PutMapping
    public void updateItem(@RequestBody Item item){
        item.setCreateTime(new Date());
        item.setStatus(null);
        itemService.updateById(item);
    }
    //删除商品
    @DeleteMapping("{id}")
    public void deleteItemById(@PathVariable("{id}") Long id){
        itemService.removeById(id);
    }
    //根据id修改库存数量
    @PutMapping("/stock/{itemId}/{num}")
    //请求参数 根据某个商品id来改变数量
    public void updateStock(@PathVariable("{itemId}") Long itemId,@PathVariable("{num}") Integer num){
        itemService.deduckStock(itemId,num);
    }
}
